|
|
|
|
|
|
|
Figure 9.7
Using named formats enhances the appearance of date information. |
|
|
|
|
|
|
|
|
The Format function uses the output of the Now function and prints only the part represented by the letter codes. A complete listing of codes is available in the Help system, under the topic "User-defined date formats." |
|
|
|
|
|
|
|
|
You just learned how to format dates. Visual Basic also includes several functions used for working with dates as values, similar to the way you work with numbers in an equation. This capability is possible because of the Visual Basic Date data type, which stores a date (and time) in a format that can be used by the various functions. As you may have noticed, the Format function and many other functions accept a date parameter that is of the type String or Date. However, some functions accept only a variable that is actually a date. To convert a string to a date, you can use the CDate function. However, be careful because an invalid string causes an error: |
|
|
|
|
|
|
|
|
Print CDate("November 23, 1963") 'Works returns 11/23/63
Print CDate("oops") 'Causes an error message! |
|
|
|
|
|
|
|
|
To determine whether a string can be converted to a valid date, use the IsDate function. In the preceding example, this function would return True and False, respectively. |
|
|
|
|
|
|
|
|
Extracting Parts of a Date |
|
|
|
|
|
|
|
|
If you need to work with dates in an automated fashion, you might want to extract part of a date. Suppose, for example, you need to schedule a process to run every Wednesday. In previous sections, you saw that you can determine the weekday number by using the WeekDay function and determine the current date and time by using the Now function. As with many things in Visual Basic, you can perform this task in several additional ways. For example, you can use the Format function to retrieve the weekday number, as follows: |
|
|
|
|
|
|
|
|
If Format(Now, "w") = 4 Then RunTheProcess |
|
|
|
|
|
|
|
|
Visual Basic also includes functions to retrieve the day, month, and year. They, of course, are called Day, Month, and Year. |
|
|
|
|
|
|
|
|
Working with Date Intervals |
|
|
|
|
|
|
|
|
Two other useful functions for working with dates are DateAdd and DateDiff. You can use the DateAdd function to add any type of interval to a date. It returns the resulting date. For example, if you have a program that must always print a report for yesterday's date, use DateAdd to determine what that day is: |
|
|
|
|
|